# -*- coding: utf-8 -*-
from flask import Flask, jsonify, render_template, g
from flask.globals import request
from views.user_views import user_view
from views.main_views import main
from views.thing_views import thing_views
from restful.api import api
from dao.engine import init_engine
from flaskext.babel import Babel

app = Flask(__name__);
app.config.from_pyfile(filename="web.cfg", silent=False);
init_engine(app); 
babel = Babel(app);

app.register_blueprint(main);
app.register_blueprint(user_view, url_prefix='/user');
app.register_blueprint(api, url_prefix="/api");
app.register_blueprint(thing_views, url_prefix="/thing");

@app.errorhandler(Exception)
def error(error=None):
    if request.headers.get("content-type", None) != "application/json":
        data = {"status": "ERROR", "message": str(error) if error else ""};
        resp = jsonify(data);
        return resp; 
    else:
        return render_template("error/error404.html", error=str(error) if error else "", url=request.url);

@app.errorhandler(404)
def error404(error=None):
    if request.headers.get("content-type", None) != "application/json":
        return render_template("error/error404.html", error=str(error) if error else "", url=request.url);
    else:
        error = {"status": "ERROR", "message": str(error) if error else "Bad request: " + request.url};
        return jsonify(error);
    
@babel.localeselector
def get_locale(): 
    """ 
    # if a user is logged in, use the locale from the user settings
    user = getattr(g, 'user', None)
    if user is not None:
        app.logger.debug("user.locale: " + user.locale);
        return user.locale

    result = request.accept_languages.best_match(['zh', 'zh_TW', 'zh_CN', 'en']);
    """
    return app.config.get("BABEL_DEFAULT_LOCALE", "en"); 

@babel.timezoneselector
def get_timezone():
    """
    user = getattr(g, 'user', None)
    if user is not None and user.timezone != None:
        return user.timezone;
    """
    return app.config.get("BABEL_DEFAULT_TIMEZONE", "UTC");

if __name__ == "__main__":
    app.run(host="127.0.0.1", port=5000);

